package com.xyh.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xyh.base.ResponseConstant;
import com.xyh.base.ResultAPI;
import com.xyh.config.cache.RedisCache;
import com.xyh.config.security.vo.LoginUser;
import com.xyh.config.sysLog.SysLog;
import com.xyh.pojo.User;
import com.xyh.service.EmailService;
import com.xyh.service.UserService;
import com.xyh.utils.JwtUtil;
import com.xyh.vo.request.student.ResetPassReqVO;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 在这个Controller内，都是不需要进行框架认证的
 */
@Slf4j
@RestController("LoginController")
@RequestMapping("/user/")
public class LoginController {

    private UserService userService;
    private EmailService emailService;
    private RedisCache redisCache;
    private PasswordEncoder passwordEncoder;



    @Autowired
    public LoginController(UserService userService,EmailService emailService,RedisCache redisCache,PasswordEncoder passwordEncoder) {
        this.userService = userService;
        this.emailService = emailService;
        this.redisCache = redisCache;
        this.passwordEncoder = passwordEncoder;
    }

    /**
     * 登录
     * @return
     */
    @PostMapping("login")
    public ResultAPI<Map<String,String>> login(@RequestBody User user){
        Map<String, String> login = userService.login(user);
        return new ResultAPI<>(200,"登录成功",login);
    }

    /**
     * 登出
     * @return
     */
    @SysLog(content = "退出了Edu考试系统")
    @PostMapping("logout/{token}")
    public ResultAPI<String> logout(@PathVariable String token){
        userService.logout(token);
        return new ResultAPI<>(ResponseConstant.SUCCESS,"退出成功","");
    }

    @GetMapping("/info")
    public ResultAPI<User> getInfo(@RequestParam String token, HttpServletRequest  request){
        String redisKey = "";
        String account ="";
        token = request.getHeader("token");
        try {
            Claims claims = JwtUtil.parseJWT(token);
            account = claims.getSubject();
            redisKey = "edu-login:"+account;
        } catch (Exception e) {
            e.printStackTrace();
        }
        Object obj = redisCache.getCacheObject(redisKey);
        LoginUser loginUser = JSON.parseObject(JSON.toJSONString(obj), LoginUser.class);

        User user = null;
        if(!Objects.isNull(loginUser)){
            user = loginUser.getUser();
            String url = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+"/avatar/";
            if(!user.getImagePath().contains(url)){
                url = url + user.getImagePath();
                user.setImagePath(url);
            }
        }else{
            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(User::getAccount,account);
            user = userService.getOne(wrapper);
            String url = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+"/avatar/"+user.getImagePath();
            user.setImagePath(url);
        }
        return new ResultAPI<>(ResponseConstant.SUCCESS,"查询成功",user);
    }

    /**
     * 注册
     * @return
     */
    @PostMapping("register")
    public ResultAPI<String> register(@RequestBody  User user){
        String pass = passwordEncoder.encode(user.getPassword());
        user.setPassword(pass);
        user.setImagePath("default.jpg");
        boolean flag = userService.save(user);
        if(flag){
            return new ResultAPI<>(ResponseConstant.SUCCESS,"注册成功","");
        }
        return new ResultAPI<>(ResponseConstant.FAILED,"注册失败，请检查网络设施","");
    }

    @GetMapping("validAccount/{account}")
    public ResultAPI<Boolean> validAccount(@PathVariable String account){
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getAccount,account);
        User user = userService.getOne(wrapper);
        if(user != null){
            return new ResultAPI<>(ResponseConstant.SUCCESS,"",true);
        }
        return new ResultAPI<>(ResponseConstant.SUCCESS,"",false);
    }

    /**
     * 后期可以使用Redis来判断这个账户，在指定的时间请求了多少次验证码，超过次数不给发送
     * @param userEmail
     * @return
     */
    @GetMapping("sendCode/{userEmail}")
    public ResultAPI<String> sendCode(@PathVariable String userEmail){
        String code = emailService.sendCode(userEmail);
        redisCache.setCacheObject(userEmail,code,5, TimeUnit.MINUTES);
        return new ResultAPI<>(ResponseConstant.SUCCESS,"发送成功",code);
    }

    @PostMapping("resetPass")
    public ResultAPI<String> resetPass(@RequestBody ResetPassReqVO vo){

        Boolean flag = userService.resetPass(vo);
        if(flag){
            return new ResultAPI<>(ResponseConstant.SUCCESS,"密码重置成功，请注意查收邮箱","");
        }
        return new ResultAPI<>(ResponseConstant.FAILED,"验证失败，请重试","");
    }



}
